package com.company.project.util;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class ExcelUtils {

    private final static Logger log = LoggerFactory.getLogger(ExcelUtils.class);

    private final static String EXCEL2003 = "xls";
    private final static String EXCEL2007 = "xlsx";


    public static <T> List<T> readExcel(MultipartFile file, Class<T> cls) throws IOException {
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        return readExcel(inputStream, fileName, cls);
    }

    public static <T> List<T> readExcel(InputStream inputStream, String fileName, Class<T> cls) {
        List<T> dataList = new ArrayList<>();

        Workbook workbook = null;
        try {
            if (fileName.endsWith(EXCEL2007)) {
                workbook = new XSSFWorkbook(inputStream);
            } else if (fileName.endsWith(EXCEL2003)) {
                workbook = new HSSFWorkbook(inputStream);
            }

            if (workbook != null) {
                return null;
            }

            //类映射  注解 value-->bean columns
            Map<String, List<Field>> classMap = new HashMap<>();
            Field[] fields = cls.getDeclaredFields();
            for (Field field : fields) {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                if (annotation != null) {
                    String value = annotation.value();
                    if (StringUtils.isBlank(value)) {
                        continue;
                    }
                    if (!classMap.containsKey(value)) {
                        classMap.put(value, new ArrayList<>());
                    }
                    field.setAccessible(true);
                    classMap.get(value).add(field);
                }
            }
            //索引-->columns
            Map<Integer, List<Field>> reflectionMap = new HashMap<>();
            Sheet sheet = workbook.getSheetAt(0);//默认读取第一个sheet

            boolean firstRow = true;
            for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);

                if (firstRow) {//首行  提取注解
                    for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                        Cell cell = row.getCell(j);
                        String cellValue = getCellValue(cell);
                        if (classMap.containsKey(cellValue)) {
                            reflectionMap.put(j, classMap.get(cellValue));
                        }
                    }
                    firstRow = false;
                } else {
                    if (row == null) {//忽略空白行
                        continue;
                    }

                    try {
                        T t = cls.newInstance();
                        boolean allBlank = true;//判断是否为空白行
                        for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                            if (reflectionMap.containsKey(j)) {
                                Cell cell = row.getCell(j);
                                String cellValue = getCellValue(cell);
                                if (StringUtils.isNotBlank(cellValue)) {
                                    allBlank = false;
                                }
                                List<Field> fieldList = reflectionMap.get(j);
                                for (Field field : fieldList) {
                                    try {
                                        handleField(t, cellValue, field);
                                    } catch (Exception e) {
                                        log.error(String.format("reflect field:%s value:%s exception!", field.getName(), cellValue), e);
                                    }
                                }
                            }
                        }
                        if (!allBlank) {
                            dataList.add(t);
                        } else {
                            log.warn(String.format("row:%s is blank ignore!", i));
                        }
                    } catch (Exception e) {
                        log.error(String.format("parse row:%s exception!", i), e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("parse excel exception!", e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
                }
            }
        }
        return dataList;
    }

    private static <T> void handleField(T t, String value, Field field) throws Exception {
        Class<?> type = field.getType();
        if (type == null || type == void.class || StringUtils.isBlank(value)) {
            return;
        }
        if (type == Object.class) {
            field.set(t, value);
        } else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {//数字类型
            if (type == int.class || type == Integer.class) {
                field.set(t, NumberUtils.toInt(value));
            } else if (type == long.class || type == Long.class) {
                field.set(t, NumberUtils.toLong(value));
            } else if (type == byte.class || type == Byte.class) {
                field.set(t, NumberUtils.toByte(value));
            } else if (type == short.class || type == Short.class) {
                field.set(t, NumberUtils.toShort(value));
            } else if (type == double.class || type == Double.class) {
                field.set(t, NumberUtils.toDouble(value));
            } else if (type == float.class || type == Float.class) {
                field.set(t, NumberUtils.toFloat(value));
            } else if (type == char.class || type == Character.class) {
                field.set(t, CharUtils.toChar(value));
            } else if (type == boolean.class) {
                field.set(t, BooleanUtils.toBoolean(value));
            } else if (type == BigDecimal.class) {
                field.set(t, new BigDecimal(value));
            }
        } else if (type == Boolean.class) {
            field.set(t, BooleanUtils.toBoolean(value));
        } else if (type == Date.class) {
            field.set(t, getDateByStr(value));

        } else if (type == String.class) {
            field.set(t, value);
        } else {
            Constructor<?> constructor = type.getConstructor(String.class);
            field.set(t, constructor.newInstance(value));
        }
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == CellType.NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return DateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == CellType.STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == CellType.FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == CellType.BLANK) {
            return "";
        } else if (cell.getCellType() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == CellType.ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }

    }

    public static <T> void writeExcel(String path, List<T> dataList, Class<T> cls, String sheetName) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try (Workbook wb = getExcelWorkbook(dataList, cls, sheetName);
             FileOutputStream fos = new FileOutputStream(file);) {
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T> void  downloadExcel(HttpServletResponse response, String fileName, String sheetName, List<T> dataList, Class<T> cls) {
        try (SXSSFWorkbook workbook = getExcelWorkbook(dataList, cls, sheetName);
             ServletOutputStream output = response.getOutputStream();) {

            Properties pro = System.getProperties();
            String encoding = pro.getProperty("file.encoding");
            response.reset();
            response.setCharacterEncoding(encoding);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");


            IOUtils.write(workbook, output);
            output.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public static <T> SXSSFWorkbook getExcelWorkbook(List<T> dataList, Class<T> cls, String sheetName) {
        Field[] fields = cls.getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields).filter(field -> {
            ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
            if (annotation != null && annotation.col() > 0) {
                field.setAccessible(true);
                return true;
            }
            return false;
        }).sorted(Comparator.comparing(field -> {
            int col = 0;
            ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
            if (annotation != null) {
                col = annotation.col();
            }
            return col;
        })).collect(Collectors.toList());

        SXSSFWorkbook wb = new SXSSFWorkbook(500);
        SXSSFSheet sheet = wb.createSheet(sheetName);
        AtomicInteger ai = new AtomicInteger();

        {
            Row row = sheet.createRow(ai.getAndIncrement());
            AtomicInteger aj = new AtomicInteger();

            //写入头部
            fieldList.forEach(field -> {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                String columnName = "";
                if (annotation != null) {
                    columnName = annotation.value();
                }
                Cell cell = row.createCell(aj.getAndIncrement());
                CellStyle cellStyle = wb.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.CENTER);

                Font font = wb.createFont();
                cellStyle.setFont(font);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(columnName);
            });
        }

        if (CollectionUtils.isNotEmpty(dataList)) {
            dataList.forEach(t -> {
                SXSSFRow row = sheet.createRow(ai.getAndIncrement());
                AtomicInteger aj = new AtomicInteger();

                fieldList.forEach(field -> {
                    Class<?> type = field.getType();

                    Object value = "";
                    try {
                        value = field.get(t);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    SXSSFCell cell = row.createCell(aj.getAndIncrement());

                    if (value != null) {
                        if (type == Date.class) {
//                            String dateValue = DateUtils.formatDate(DateUtils.stampToDate(Long.valueOf(value.toString())),"yyyy-MM-dd");;
//                            cell.setCellValue(dateValue);
                            cell.setCellValue(stampToDate(Long.valueOf(value.toString())));
                        } else if (Number.class.isAssignableFrom(type)) {
                            cell.setCellType(CellType.NUMERIC);
                            if (type == Integer.class) {
                                cell.setCellValue(Integer.valueOf(value.toString()));
                            } else if (type == Long.class) {
                                cell.setCellValue(Long.valueOf(value.toString()));
                            } else if (type == Float.class) {
                                cell.setCellValue(Float.valueOf(value.toString()));
                            } else if (type == Double.class) {
                                cell.setCellValue(Double.valueOf(value.toString()));
                            } else if (type == BigDecimal.class) {
                                cell.setCellValue(new BigDecimal(value.toString()).floatValue());
                            }

                        } else {
                            cell.setCellValue(value.toString());
                        }
                    }
                });
            });

        }

        //冻结窗格
        sheet.createFreezePane(0, 1, 0, 1);
        return wb;

    }

    /**
     * 字符转日期
     *
     * @param dateStr
     * @return
     */
    public static Date getDateByStr(String dateStr) {
        SimpleDateFormat formatter = null;
        if (dateStr == null) {
            return null;
        } else if (dateStr.length() == 10) {
            formatter = new SimpleDateFormat("yyyy-MM-dd");
        } else if (dateStr.length() == 16) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        } else if (dateStr.length() == 19) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else if (dateStr.length() > 19) {
            dateStr = dateStr.substring(0, 19);
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            return null;
        }
        try {
            return formatter.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }

    /*
     * 将时间戳转换为时间
     */
    public static Date stampToDate(Long s) {
        Date date = new Date(s);
        return date;
    }

}